<?php
/**
 * Created by PhpStorm.
 * User: Monkey
 * Date: 2021/10/13
 * Time: 11:27
 * Desc: 产品
 */
declare (strict_types=1);

namespace app\api\controller;

use app\api\base\controller\Base;
use app\extend\model\ProductData;
use think\facade\Db;

class Product extends Base
{
    public function getAll()
    {
        $productList = \app\extend\model\Product::where([
            ['sale', '<>', 0],
            ['is_delete', '=', 0]
        ])->field('id,product_name,sale,img_url')->order(['sort' => 'asc', 'id' => 'asc'])->limit(100)->select();

        if (!$productList->isEmpty()) {
            foreach ($productList as $productVal) {
                $productDataInfo = ProductData::where([
                    ['product_id', '=', $productVal->id]
                ])->field('id,price,low,high')->find();
                $productVal->priceb = round((($productDataInfo['price'] - $productVal['sale']) / $productVal['sale']) * 100, 2);
                if ($productDataInfo['price'] > $productVal['sale']) {
                    $productVal->class = 'red';
                } else {
                    $productVal->class = 'green';
                }
                $productVal->price = $productDataInfo['price'];
                $productVal->low = $productDataInfo['low'];
                $productVal->high = $productDataInfo['high'];
            }
        }

        return json(_S('获取成功', $productList));
    }

    /**
     * 产品金额
     */
    public function getPriceDetail()
    {
        $id = input('id/d', 0);

        $productInfo = \app\extend\model\Product::where([
            ['id', '=', $id]
        ])->field('id,sale')->find();

        $productDataInfo = ProductData::where([
            ['product_id', '=', $id]
        ])->field('id,price')->find();

        $zhangdie = round(($productDataInfo['price'] - $productInfo['sale']), 2);
        $zhangfu = round((($productDataInfo['price'] - $productInfo['sale']) / $productInfo['sale']) * 100, 2);

        $maizhang = rand(100, 999);
        $maidie = rand(100, 999);

        $maizhangXhx = floor(($maizhang / ($maizhang + $maidie)) * 100);

        return json(_S('获取成功',[
            'price' => $productDataInfo->price,
            'maizhang_xhx' => $maizhangXhx,
            'maidie_xhx' => 100 - $maizhangXhx,
            'zhangdie' => $zhangdie,
            'zhangfu' => $zhangfu,
            'maizhang' => $maizhang,
            'maidie' => $maidie,
        ]));
    }

    /**
     * 详情
     */
    public function getDetail()
    {
        $id = input('id/d', 0);

        $productInfo = \app\extend\model\Product::where([
            ['id', '=', $id]
        ])->find();

        $productDataInfo = ProductData::where([
            ['product_id', '=', $id]
        ])->find();

        $websiteConfigInfo = \app\extend\model\WebsiteConfig::where([
            ['id','=',1]
        ])->find();

        $userInfo = \app\extend\model\User::where([
            ['id', '=', self::$UserInfo['id']]
        ])->field('balance')->find();

        return json(_S('获取成功', [
            'product' => $productInfo,
            'product_data' => $productDataInfo,
            'balance' => $userInfo['balance'],
            'moneys' => explode('|', $websiteConfigInfo['investment']),
            'times' => empty($productInfo['time']) ? [] : explode(',', $productInfo['time']),
            'scales' => empty($productInfo['scale']) ? [] : explode(',', $productInfo['scale'])
        ]));
    }

    /**
     * 获取K线数据
     */
    public function getKlineAll()
    {
        $id = input('id/d', 0);
        $num = input('num/d', 30);
        $interval = input('interval', 1);

        //判断时间
        switch ($interval) {
            case '1':
                $dataTime = 60;
                break;
            case '5':
                $dataTime = 300;
                break;
            case '15':
                $dataTime = 900;
                break;
            case '30':
                $dataTime = 1800;
                break;
            case '60':
                $dataTime = 3600;
                break;
            case 'd':
                $dataTime = 86400;
                break;
            case 'm':
                $dataTime = 2592000;
                break;
        }

        $productInfo = \app\extend\model\Product::where([
            ['id', '=', $id],
            ['is_delete', '=', 0]
        ])->field('id,product_name_en,type')->find();

        if(in_array($productInfo->type,['Manual','OpenExchangeRates'])){
            $productDataInfo = ProductData::where([
                ['product_id', '=', $id],
                ['is_delete', '=', 0]
            ])->field('id,high,low,open,close')->find()->toArray();

            $jsonTime = time();
            $result = [];

            for ($i = 1; $i <= $num; $i++) {
                $randss = rand(1, 100);
                $jsonTime = $jsonTime - $dataTime - 150;
                $result[] = [
                    'timestamp' => $jsonTime * 1000,
                    'volume' => ($productDataInfo['high'] + $randss) - ($productDataInfo['low'] + $randss),
                    'open' => $productDataInfo['open'] + $randss,
                    'low' => $productDataInfo['low'] + $randss,
                    'high' => $productDataInfo['high'] + $randss,
                    'close' => $productDataInfo['close'] + $randss
                ];
            }
            $dataArr = [];
            for ($i = count($result) - 1; $i > -1; $i--) {
                $dataArr[] = $result[$i];
            }
        } else {
            $className = '\\app\\extend\\kline\\'.$productInfo->type;
            $dataArr = $className::getKline($productInfo->product_name_en,$interval,$num);
        }

        return json(_S('获取成功', $dataArr));
    }

    /**
     * 下单
     */
    public function placeOrder()
    {
        if (request()->isPost()) {
            $id = input('id/d', 0);
            $type = input('type/d', 1);
            $money = input('money', 0);
            $scale = input('scale', 0);
            $time = input('time', 0);
            $newPrice = input('new_price', 0);

            $userInfo = \app\extend\model\User::where([
                ['id', '=', self::$UserInfo['id']]
            ])->field('balance,status')->find();

            //验证用户是否被冻结
            if($userInfo['status'] != 0){
                return json(_E('您的账户已被冻结！'));
            }

            $websiteConfigInfo = \app\extend\model\WebsiteConfig::where([
                ['id', '=', 1]
            ])->find();

            //判断最低购买金额
            if($money < $websiteConfigInfo['order_min_money']){
                return json(_E('抱歉！单笔持仓最低！'.$websiteConfigInfo['order_min_money']));
            }

            $productInfo = \app\extend\model\Product::where([
                ['id', '=', $id]
            ])->field('id,product_name,time,scale')->find();

            $timeArr = explode(',',$productInfo->time);
            $key = array_search($time / 60, $timeArr);
            $scaleArr = explode(',',$productInfo->scale);
            if($scaleArr[$key] != $scale){
                return json(_E('参数错误'));
            }

            if($time == 120 && $userInfo->balance < 30000){//2分钟的账户余额要大于等于3万
                return json(_E('账户余额要大于等于3万'));
            }

            if($time == 180 && $userInfo->balance < 50000){//2分钟的账户余额要大于等于5万
                return json(_E('账户余额要大于等于5万'));
            }

            $saveData['uid'] = self::$UserInfo['id'];
            $saveData['buytime'] = date('Y-m-d H:i:s');
            $saveData['endprofit'] = $time;
            $saveData['product_id'] = $id;
            $saveData['type'] = $type;//1涨，2跌
            $saveData['buyprice'] = $newPrice;
            $saveData['endloss'] = $scale;//收益
            $saveData['selltime'] = date('Y-m-d H:i:s', strtotime($saveData['buytime']) + $saveData['endprofit']);
            $saveData['fee'] = $money;
            $saveData['product_name'] = $productInfo->product_name;
            $saveData['status'] = 0;
            $saveData['sx_fee'] = round($saveData['fee'] * $websiteConfigInfo['platform_fee'] / 100, 2);
            $allfee = $saveData['fee'] + $saveData['sx_fee'];
            $saveData['commission'] = $userInfo['balance'] - $allfee;

            //判断用户余额
            if ($userInfo['balance'] < $allfee) {
                return json(_E('您得余额不足，请充值！'));
            }

            try {
                // 启动事务
                Db::startTrans();

                \app\extend\model\Order::insert($saveData);

                //扣除用户余额
                \app\extend\model\User::where([
                    ['id', '=', self::$UserInfo['id']]
                ])->update([
                    'balance' => $userInfo['balance'] - $allfee,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

                Db::commit();
                return json(_S('下单成功'));
            } catch (\Exception $e) {
                Db::rollback();
                return json(_E('下单失败', $e->getMessage()));
            }
        }
    }
}
